package org.jeecg.modules.demo.ch.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.ch.Utils.DateUtil;
import org.jeecg.modules.demo.ch.common.CommonMst;
import org.jeecg.modules.demo.ch.common.PageList;
import org.jeecg.modules.demo.ch.entity.ChWeeklyReportFeedback;
import org.jeecg.modules.demo.ch.entity.WeeklyReportFeedback;
import org.jeecg.modules.demo.ch.service.IChWeeklyReportFeedbackService;
import org.jeecg.modules.demo.ch.service.IWeeklyReportFeedbackService;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 周报反馈报表
 * @Author: jeecg-boot
 * @Date: 2022-11-14
 * @Version: V1.0
 */
@Api(tags = "周报反馈报表")
@RestController
@RequestMapping("/ch/chWeeklyReportFeedback")
@Slf4j
public class ChWeeklyReportFeedbackController extends JeecgController<ChWeeklyReportFeedback, IChWeeklyReportFeedbackService> {
    @Autowired
    private IChWeeklyReportFeedbackService chWeeklyReportFeedbackService;
    @Autowired
    private IWeeklyReportFeedbackService weeklyReportFeedbackService;

    /**
     * 分页列表查询
     *
     * @param chWeeklyReportFeedback
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "周报反馈报表-分页列表查询")
    @ApiOperation(value = "周报反馈报表-分页列表查询", notes = "周报反馈报表-分页列表查询")
//    @GetMapping(value = "/list")
    // 需要将前端将list请求地址改成此地址
    @GetMapping(value = "/sqlList")
    @PermissionData(pageComponent = "weekReport/ChWeeklyReportFeedbackList")
    public Result<PageList<WeeklyReportFeedback>> queryPageList(ChWeeklyReportFeedback chWeeklyReportFeedback,
                                                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                @RequestParam(name = "pageSize", defaultValue = "1000") Integer pageSize,
                                                                HttpServletRequest req) {
//		QueryWrapper<ChWeeklyReportFeedback> queryWrapper = QueryGenerator.initQueryWrapper(chWeeklyReportFeedback, req.getParameterMap());
//		LambdaQueryWrapper<WeeklyReportFeedback> weeklyReportFeedbackLambdaQueryWrapper = new QueryWrapper<WeeklyReportFeedback>().lambda();
        String beginTime = chWeeklyReportFeedback.getBeginTime();
        String endTime = chWeeklyReportFeedback.getEndTime();
        log.info("chWeeklyReportFeedback:{}", chWeeklyReportFeedback);
        if (StringUtils.hasLength(beginTime)) {
            beginTime = chWeeklyReportFeedback.getBeginTime().substring(1, 11);
        }
        if (StringUtils.hasLength(endTime)) {
            endTime = chWeeklyReportFeedback.getEndTime().substring(1, 11);
        }
        String executor = chWeeklyReportFeedback.getExecutor();//执行人
        String executionStatus = chWeeklyReportFeedback.getExecutionStatus();//执行状态
        String classification = chWeeklyReportFeedback.getClassification();//分类
        String weeklyMeetTitle = chWeeklyReportFeedback.getWeeklyMeetTitle();//标题
        String representation = chWeeklyReportFeedback.getRepresentation();//代表事项

        SimpleDateFormat sf = new SimpleDateFormat(CommonMst.WEEKLYREPORT.DATEFORMAT);
        String monday = sf.format(DateUtil.getLastWeek().get("monday"));//上周一
        String sunday = sf.format(DateUtil.getLastWeek().get("sunday"));//上周日
        //默认查询上一周的
        if (!StringUtils.hasLength(beginTime) && !StringUtils.hasLength(endTime)) {
            beginTime = monday;
            endTime = sunday;
        }
        //结束日期+1天
        if (StringUtils.hasLength(endTime)) {
            LocalDate date = LocalDate.parse(endTime);
            LocalDate localDate = date.plusDays(1);
            DateTimeFormatter df = DateTimeFormatter.ofPattern(CommonMst.WEEKLYREPORT.DATEFORMAT);
            endTime = localDate.format(df);
        }
        //就是调用这个QueryGenerator.installAuthJdbc方法获取权限sql
        String permissionSql = QueryGenerator.installAuthJdbc(WeeklyReportFeedback.class);

        int num = weeklyReportFeedbackService.selectChWeeklyReportFeedbackListTotalByTime(executor, executionStatus, classification, weeklyMeetTitle, representation, beginTime, endTime,permissionSql);
        PageList<WeeklyReportFeedback> weeklyReportFeedbackPageList = new PageList<>(pageNo, pageSize, num);
        List<WeeklyReportFeedback> weeklyReportFeedbackList = weeklyReportFeedbackService.selectChWeeklyReportFeedbackListByTime(pageNo, pageSize, executor, executionStatus, classification, weeklyMeetTitle, representation, beginTime, endTime, permissionSql);
        weeklyReportFeedbackPageList.setRecords(weeklyReportFeedbackList);
        return Result.OK(weeklyReportFeedbackPageList);
    }

    /**
     * 添加
     *
     * @param chWeeklyReportFeedback
     * @return
     */
    @AutoLog(value = "周报反馈报表-添加")
    @ApiOperation(value = "周报反馈报表-添加", notes = "周报反馈报表-添加")
    //@RequiresPermissions("org.jeecg.modules.demo:ch_weekly_report_feedback:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody ChWeeklyReportFeedback chWeeklyReportFeedback) {
        chWeeklyReportFeedbackService.save(chWeeklyReportFeedback);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param chWeeklyReportFeedback
     * @return
     */
    @AutoLog(value = "周报反馈报表-编辑")
    @ApiOperation(value = "周报反馈报表-编辑", notes = "周报反馈报表-编辑")
    //@RequiresPermissions("org.jeecg.modules.demo:ch_weekly_report_feedback:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody ChWeeklyReportFeedback chWeeklyReportFeedback) {
        chWeeklyReportFeedbackService.updateById(chWeeklyReportFeedback);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "周报反馈报表-通过id删除")
    @ApiOperation(value = "周报反馈报表-通过id删除", notes = "周报反馈报表-通过id删除")
    //@RequiresPermissions("org.jeecg.modules.demo:ch_weekly_report_feedback:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        chWeeklyReportFeedbackService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "周报反馈报表-批量删除")
    @ApiOperation(value = "周报反馈报表-批量删除", notes = "周报反馈报表-批量删除")
    //@RequiresPermissions("org.jeecg.modules.demo:ch_weekly_report_feedback:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.chWeeklyReportFeedbackService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "周报反馈报表-通过id查询")
    @ApiOperation(value = "周报反馈报表-通过id查询", notes = "周报反馈报表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<ChWeeklyReportFeedback> queryById(@RequestParam(name = "id", required = true) String id) {
        ChWeeklyReportFeedback chWeeklyReportFeedback = chWeeklyReportFeedbackService.getById(id);
        if (chWeeklyReportFeedback == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(chWeeklyReportFeedback);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param weeklyReportFeedback
     */
    //@RequiresPermissions("org.jeecg.modules.demo:ch_weekly_report_feedback:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, WeeklyReportFeedback weeklyReportFeedback) {
        log.info("传来的参数weeklyReportFeedback:{}", weeklyReportFeedback);
        // Step.1 组装查询条件
//        LambdaQueryWrapper<WeeklyReportFeedback> weeklyReportFeedbackLambdaQueryWrapper = new QueryWrapper<WeeklyReportFeedback>().lambda();
        String beginTime = weeklyReportFeedback.getBeginTime();
        String endTime = weeklyReportFeedback.getEndTime();
        if (StringUtils.hasLength(beginTime)) {
            beginTime = weeklyReportFeedback.getBeginTime().substring(1, 11);
        }
        if (StringUtils.hasLength(endTime)) {
            endTime = weeklyReportFeedback.getEndTime().substring(1, 11);
        }
        String executor = weeklyReportFeedback.getExecutor();//执行人
        String executionStatus = weeklyReportFeedback.getExecutionStatus();//执行状态
        String classification = weeklyReportFeedback.getClassification();//分类
        String weeklyMeetTitle = weeklyReportFeedback.getWeeklyMeetTitle();//标题
        String representation = weeklyReportFeedback.getRepresentation();//代表事项

        SimpleDateFormat sf = new SimpleDateFormat(CommonMst.WEEKLYREPORT.DATEFORMAT);
        String monday = sf.format(DateUtil.getLastWeek().get("monday"));//上周一
        String sunday = sf.format(DateUtil.getLastWeek().get("sunday"));//上周日
        //默认查询上一周的
        if (!StringUtils.hasLength(beginTime) && !StringUtils.hasLength(endTime)) {
            beginTime = monday;
            endTime = sunday;
        }
        //结束日期+1天
        if (StringUtils.hasLength(endTime)) {
            LocalDate date = LocalDate.parse(endTime);
            LocalDate localDate = date.plusDays(1);
            DateTimeFormatter df = DateTimeFormatter.ofPattern(CommonMst.WEEKLYREPORT.DATEFORMAT);
            endTime = localDate.format(df);
        }
        Integer pageNo = 1;
        Integer pageSize = 1000;

        //就是调用这个QueryGenerator.installAuthJdbc方法获取权限sql
        String permissionSql = QueryGenerator.installAuthJdbc(WeeklyReportFeedback.class);
        List<WeeklyReportFeedback> exportList = weeklyReportFeedbackService.selectChWeeklyReportFeedbackListByTime(pageNo, pageSize, executor, executionStatus, classification, weeklyMeetTitle, representation, beginTime, endTime,permissionSql);
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // Step.2 获取导出数据
        if (!CollectionUtils.isEmpty(exportList)) {
            exportList = exportList.stream()
                    .filter(p -> {
                        String selections = request.getParameter("selections");
                        List<String> selectionList = null;
                        if (oConvertUtils.isNotEmpty(selections)) {
                            selectionList = Arrays.asList(selections.split(","));
                        } else {
                            //默认返回true 才表示查询的集合数据全都要
                            return true;
                        }
                        //返回  id在selectionList中的数据
                        return selectionList.contains(p.getId());
                    }).collect(Collectors.toList());
        }

        // Step.3 AutoPoi 导出Excel
        String title = "周报反馈报表";
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.FILE_NAME, title);
        mv.addObject(NormalExcelConstants.CLASS, WeeklyReportFeedback.class);
        //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
        ExportParams exportParams = new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title);
        //update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("ch_weekly_report_feedback:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ChWeeklyReportFeedback.class);
    }





}
